<template>
  <div class="w-full h-full pt-2">
    <!-- 病历 -->
    <BaseTitle :title="'病历信息'">
      <div>
        <a-button type="primary" ghost class="mx-2" @click="templateModalOpen = true">病历模板</a-button>
        <a-button class="mr-2" @click="onPrintMedical"> 打印病历单</a-button>
      </div>
    </BaseTitle>
    <a-form class="mt-4" :disabled="!store.currentPatient.jzbh">
      <div class="case-table my-2">
        <div v-for="item in WMItems" :key="item.value" class="case-item">
          <template v-if="item.label === '处置'">
            <div class="label flex-col justify-center">
              <div>医嘱</div>
              <a-button class="-ml-2" size="small" type="link" @click="onGetDispose(2, false)">获取医嘱</a-button>
            </div>
            <div class="content h-[54px]">
              <a-textarea v-model:value="formState[item.value]" :disabled="formState.isCommit === 1" placeholder="请输入" :rows="4" />
            </div>
          </template>
          <template v-else>
            <div class="label" :class="{ required: item.label === '初步诊断' }">{{ item.label }}</div>
            <div class="content h-[54px]">
              <SelectTable
                v-if="item.label === '初步诊断'"
                v-model:value="formState[item.value]"
                type="诊断"
                :disabled="!store.currentPatient.jzbh || formState.isCommit === 1"
                @select="onSelect(item.value, item.code, $event)"
              />
              <SelectTable
                v-if="item.label === '其他诊断'"
                v-model:value="formState[item.value]"
                multiple
                type="诊断"
                :auto-mark="false"
                :disabled="!store.currentPatient.jzbh || formState.isCommit === 1"
                @select="onSelect(item.value, item.code, $event, true)"
              />
              <SelectTags
                v-else
                v-model:value="formState[item.value]"
                :disabled="formState.isCommit === 1"
                show-setting
                show-new
                multiple
                type="医嘱字典"
                :search-params="{ blcybh: item.label }"
              />
            </div>
          </template>
        </div>
      </div>
      <div class="flex justify-end mt-4 mr-2">
        <a-button class="mr-4" @click="onReset">重置</a-button>
        <a-button class="mr-4" :disabled="formState.isCommit === 1" type="primary" @click="onSubmit()">保存</a-button>
      </div>
      <TemplateModal v-model:open="templateModalOpen" :mrm-code="mrmCode" @success="onTempSuccess" />
    </a-form>
  </div>
</template>
<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import SelectTags from '@/components/SelectTags'
import SelectTable from '@/components/SelectTable'
import useUserStore from '@/store/user'
import useStore from '../store'
import TemplateModal from './TemplateModal'

const { empId } = useUserStore()
const props = defineProps({
  caseData: {
    type: Object,
    default: () => ({})
  },
  activeKey: {
    type: String,
    default: ''
  }
})
const emit = defineEmits(['success'])
const store = useStore()
const formState = ref({})
const templateModalOpen = ref(false)
const saveStatus = ref() // 判断是否有初步诊断，提交按钮是否可点击
const WMItems = ref([
  { label: '主诉', value: 'bcZs' },
  { label: '病史', value: 'bcXbs' },
  { label: '既往史', value: 'bcJws' },
  { label: '家族史', value: 'bcJzs' },
  { label: '月经史', value: 'bcYjsjsys' },
  { label: '体格检查', value: 'bcTgjc' },
  { label: '辅助检查', value: 'bcFzjc' },
  { label: '初步诊断', value: 'bcLczdZdmc', code: 'bcLczdZddm' },
  { label: '其他诊断', value: 'bcQtzdZdmc', code: 'bcQtzdZddm' },
  { label: '注意事项', value: 'bcZysx' },
  { label: '处置', value: 'bcCz' }
])

//获取处置
const onGetDispose = async (state, status) => {
  const res = await post('/outp/mzys/lnkAutoZlclLinkClicked', {
    jzbh: store.currentPatient.jzbh,
    sfykbl: status ? state : undefined
  })
  if (state === 1) {
    const dataText = res.data.includes(formState.value.bcCl) ? res.data : formState.value.bcCl
    formState.value.bcCl = dataText || res.data
  } else {
    const dataText = res.data.includes(formState.value.bcCz) ? res.data : formState.value.bcCz
    formState.value.bcCz = dataText || res.data
  }
}

//获取病历类型
// const caseTypeOptions = ref([])
const mrmCode = ref()
// const getCaseType = async () => {
//   const res = await post('/common/const/getMedicalRecordMode', { mrmType: 0 })
//   caseTypeOptions.value = res.data || []
//   // mrmCode.value = res.data?.[0]?.mrmCode
// }
// 获取当前医生默认显示的病历
const getMedical = async () => {
  const res = await post('/common/masterData/getByYsbhDepartment', { empId })
  if (res.code !== 0) return message.error(res.msg)
  mrmCode.value = res.data && res.data.blmb
}
//保存病历信息
const onSubmit = async (status, state = true) => {
  const res = await post('outp/mzys/doSavePatientEMR', {
    ...formState.value,
    brId: store.currentPatient.brId,
    jzbh: store.currentPatient.jzbh,
    mrmCode: mrmCode.value,
    qtzdxx: '',
    isCxtj: status ?? undefined,
    isCommit: status ?? undefined
  })
  if (res.code !== 0) return message.error(res.msg)
  if (state) {
    message.success('保存成功')
  } else {
    message.success(status === '1' ? '提交成功' : '撤销成功')
  }
  emit('success')
}
const onTempSuccess = (data) => {
  formState.value = data
}

// 重置
const onReset = () => {
  for (const key in formState.value) {
    if (Object.hasOwnProperty.call(formState.value, key)) {
      formState.value[key] = ''
    }
  }
  formState.value.isCommit = false
}
// 打印病历单
const onPrintMedical = async () => {
  const { code, msg, data } = await post('/outp/outPrint/printrptMZBL', { brId: store.currentPatient.brId, jzbh: store.currentPatient?.jzbh })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}
watch(
  () => store.tempCase,
  () => {
    formState.value = store.tempCase
  }
)

const onSelect = (value, code, select, multiple = false) => {
  if (multiple) {
    //多选拼接
    formState.value[value] = formState.value[value] ? formState.value[value] + '，' + select.zdmc || select.mc : select.zdmc || select.mc
    formState.value[code] = formState.value[code] ? formState.value[code] + '，' + select.zddm || select.dm : select.zddm || select.dm
  } else {
    formState.value[value] = select.zdmc || select.mc
    formState.value[code] = select.zddm || select.dm
  }
}

watch(
  () => store.currentPatient.jzbh,
  () => {
    getMedical()
  }
)

watch(
  () => props.activeKey,
  (val) => {
    if (val === '1') {
      if (props.caseData?.ghzt === '3') {
        formState.value = { ...props.caseData }
        getMedical()
      }
    }
  },
  {
    immediate: true
  }
)

watch(
  () => props.caseData,
  (value) => {
    if (props.caseData?.ghzt === '3') {
      formState.value = { ...value }
      saveStatus.value = formState.value.bcLczdZddm
      store.currentMedical = formState.value
    } else {
      formState.value = { ...value }
    }
  },
  { deep: true }
)
</script>
<style lang="less" scoped>
.case-table {
  --border-color: rgba(125, 125, 125, 0.16);
  border: 1px solid var(--border-color);
  .case-item {
    display: flex;
    .required {
      position: relative;
      &::before {
        position: absolute;
        top: 8px;
        left: 8px;
        color: red;
        content: '*';
      }
    }
    .label {
      display: flex;
      align-items: center;
      width: 278px;
      height: 54px;
      padding: 8px 16px;
      background-color: #f5f5f5;
      border-right: 1px solid var(--border-color);
      border-bottom: 1px solid var(--border-color);
    }
    .label-eye {
      display: flex;
      align-items: center;
      width: 278px;
      background-color: #f5f5f5;
      border-right: 1px solid var(--border-color);
      border-bottom: 1px solid var(--border-color);
      .eye-border-left {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 94px;
        .eye-border-left-con {
          padding: 8px 16px;
        }
      }
      .eye-border-right {
        width: 184px;
        border-left: 1px solid var(--border-color);
        .eye-border-right-con {
          padding: 8px 10px 8px 16px;
          border-bottom: 1px solid var(--border-color);
        }
        .eye-border-right-con:last-child {
          border-bottom: none;
        }
      }
    }
    .content {
      flex: 1;
      overflow: hidden;
      border-bottom: 1px solid var(--border-color);
      :deep(.ant-input) {
        height: 100%;
        border: none;
        border: 1px solid transparent;
        border-radius: 0;
        &:focus {
          background: var(--edit-cell-color);
          border: 1px solid var(--primary-color);
          box-shadow: none;
        }
        &:hover {
          background: var(--bg-color);
          border: 1px solid var(--primary-color);
        }
      }
      :deep(.ant-select) {
        height: 100%;
        padding-top: 3px;
        border: 1px solid transparent;
        border-radius: 0;
        &:focus {
          background: var(--edit-cell-color);
          border: 1px solid var(--primary-color);
          box-shadow: none;
        }
        &:hover {
          background: var(--bg-color);
          border: 1px solid var(--primary-color);
        }
      }
      :deep(.ant-input-affix-wrapper) {
        height: 100%;
        background: var(--bg-color);
        border: 1px solid transparent;
        border-radius: 0;
        &-focused {
          border: 1px solid var(--primary-color);
          box-shadow: none;
        }
        &:hover {
          background: var(--bg-color);
          border: 1px solid var(--primary-color);
        }
        .ant-input {
          border: none;
        }
      }
      .eye-box {
        background-color: #f5f5f5;
        .eye-box-header-left {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 50%;
          border-right: 1px solid var(--border-color);
          border-bottom: 1px solid var(--border-color);
        }
        .eye-box-header-right {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 50%;
          border-bottom: 1px solid var(--border-color);
        }
      }
      .eye-item-box {
        border-bottom: 1px solid var(--border-color);
        .eye-box-left {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 50%;
          height: 100%;
          border-right: 1px solid var(--border-color);
          .eye-box-left-br {
            border-right: 1px solid var(--border-color);
          }
        }
        .eye-box-right {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 50%;
          height: 100%;
          .eye-box-right-br {
            border-right: 1px solid var(--border-color);
          }
        }
      }
      .eye-wrap:last-child {
        .eye-item-box {
          border-bottom: none;
        }
      }
    }
    &:last-child {
      .content,
      .label {
        align-items: flex-start;
        border-bottom: none;
      }
    }
  }
}
.no-data {
  display: flex;
  align-items: center;
  height: 100%;
  padding-left: 12px;
}
</style>
